<template>
  <div class="context-menu-container">
    <!-- 插槽 -->
    <slot></slot>

    <!-- 右键菜单组件 -->
    <div
      class="context-menu"
      :style="{ left: `${x}px`, top: `${y}px` }"
      v-if="visible"
      @click.stop
    >
      <template v-for="(item, index) in menus" :key="index">
        <!-- 先渲染分隔线（如果当前索引需要） -->
        <div class="context-menu-divider" v-if="dividers.includes(index)"></div>

        <!-- 再渲染菜单项 -->
        <div class="context-menu-item" @click="handleItemClick(item)">
          <span v-if="item.icon" class="item-icon">{{ item.icon }}</span>
          <span class="item-text">{{ item.label }}</span>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, provide } from "vue";

// 组件属性
const props = defineProps({
  // 菜单项配置
  menus: {
    type: Array,
    default: () => [],
  },
  // 分隔线位置（索引）
  dividers: {
    type: Array,
    default: () => [],
  },
});

// 组件事件
const emit = defineEmits(["click"]);

// 菜单状态
const visible = ref(false);
const x = ref(0);
const y = ref(0);

// 触发菜单的元素回调方法
let currentTargetCallback = undefined;

// 处理菜单项点击
const handleItemClick = (menu) => {
  visible.value = false;
  currentTargetCallback(menu);
};

// 显示菜单
const showMenu = (e, callback) => {
  currentTargetCallback = callback;

  e.preventDefault();
  // 计算菜单位置，避免超出视口
  const { clientX, clientY } = e;
  const menuWidth = 180;
  const menuHeight = props.menus.length * 36 + props.dividers.length * 10;

  // 处理右侧溢出
  x.value =
    clientX + menuWidth > window.innerWidth
      ? window.innerWidth - menuWidth - 10
      : clientX;

  // 处理底部溢出
  y.value =
    clientY + menuHeight > window.innerHeight
      ? window.innerHeight - menuHeight - 10
      : clientY;

  visible.value = true;
};

// 隐藏菜单
const hideMenu = () => {
  visible.value = false;
};

provide("showMenu", showMenu);
provide("hideMenu", hideMenu);
</script>

<style scoped lang="scss">
.context-menu-container {
  .context-menu {
    position: fixed;
    width: 180px;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    padding: 5px 0;
    z-index: 9999;
    transition: opacity 0.15s ease;

    .context-menu-item {
      display: flex;
      align-items: center;
      padding: 8px 16px;
      cursor: pointer;
      font-size: 14px;
      color: #333;
      transition: background-color 0.2s;

      &:hover {
        background-color: #f5f7fa;
        color: #165dff;
      }

      .item-icon {
        margin-right: 8px;
        font-size: 16px;
      }
    }

    .context-menu-divider {
      height: 1px;
      background-color: #c4c4c4;
      margin: 4px 10px;
    }
  }
}
</style>
